package com.foodorder.repository;

import com.foodorder.entity.Coupon;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 优惠券数据访问接口
 */
@Repository
public interface CouponRepository extends JpaRepository<Coupon, Long>, JpaSpecificationExecutor<Coupon> {
    
    /**
     * 根据店铺ID查找优惠券
     */
    List<Coupon> findByStoreIdAndStatus(Long storeId, Coupon.CouponStatus status);
    
    /**
     * 查找平台优惠券
     */
    List<Coupon> findByStoreIdIsNullAndStatus(Coupon.CouponStatus status);
    
    /**
     * 根据状态统计优惠券数量
     */
    long countByStatus(Coupon.CouponStatus status);
    
    /**
     * 查找可用的优惠券
     */
    @Query("SELECT c FROM Coupon c WHERE c.status = :status AND c.startTime <= CURRENT_TIMESTAMP AND c.endTime >= CURRENT_TIMESTAMP")
    List<Coupon> findAvailableCoupons(@Param("status") Coupon.CouponStatus status);
    
    /**
     * 查找可抢的红包
     */
    @Query("SELECT c FROM Coupon c WHERE c.status = :status AND c.startTime <= CURRENT_TIMESTAMP AND c.endTime >= CURRENT_TIMESTAMP AND (c.totalQuantity = -1 OR c.claimedCount < c.totalQuantity)")
    List<Coupon> findGrabbableCoupons(@Param("status") Coupon.CouponStatus status);
    
    /**
     * 根据类型查找优惠券
     */
    List<Coupon> findByTypeAndStatus(Coupon.CouponType type, Coupon.CouponStatus status);
    
    /**
     * 查找即将过期的优惠券
     */
    @Query("SELECT c FROM Coupon c WHERE c.endTime BETWEEN :startDate AND :endDate")
    List<Coupon> findExpiringCoupons(@Param("startDate") LocalDateTime startDate, @Param("endDate") LocalDateTime endDate);
}